package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.R;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.User;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
@Component
public class LoginCheckFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        String[] loginUrls = {
                "/user/login",
                "/user/sendMsg",
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**"};
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        HttpServletRequest req = (HttpServletRequest) request;
        String requestURI = req.getRequestURI();
        for (String loginUrl : loginUrls) {
            boolean match = antPathMatcher.match(loginUrl, requestURI);
            if (match) {
                chain.doFilter(request, response);
                return;
            }
        }
        Employee loginEmployee = (Employee) req.getSession().getAttribute("loginEmployee");
        User loginUser = (User) req.getSession().getAttribute("loginUser");
        if (loginEmployee != null || loginUser != null) {
            //登陆成功,向ThreadLocal存入当前用户id
            if (loginEmployee != null){
                Long id = loginEmployee.getId();
                UserHolder.setUserId(id);
            }

            if (loginUser != null){
                Long id1 = loginUser.getId();
                UserHolder.setUserId(id1);
            }

            chain.doFilter(request, response);//放行
            //回来的代码,需要释放ThreadLocal中存储的用户id,避免内存溢出的风险
            UserHolder.release();
        } else {
            //未登录
            HttpServletResponse resp = (HttpServletResponse) response;
            R<Object> notlogin = R.error("NOTLOGIN");
            String jsonString = JSON.toJSONString(notlogin);
            resp.getWriter().write(jsonString);
        }
    }
}
